package com.ibm.java;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.ibm.cps.message.RuleMetaMessage;

public class Serialization {

	public static String hexStr2Str(String hexStr) {
		String str = "0123456789ABCDEF";
		char[] hexs = hexStr.toCharArray();
		byte[] bytes = new byte[hexStr.length() / 2];
		int n;

		for (int i = 0; i < bytes.length; i++) {
			n = str.indexOf(hexs[2 * i]) * 16;
			n += str.indexOf(hexs[2 * i + 1]);
			bytes[i] = (byte) (n & 0xff);
		}
		return new String(bytes);
	}

	public void byte2String() {
		String a = "ef";
		System.out.println(hexStr2Str(a));
	}

	public static void main(String[] args) throws Exception {
		Serialization serialization = new Serialization();
		serialization.byte2String();
		RuleMetaMessage rule = new RuleMetaMessage("user", "rule", "1",
				"topic", "1", "ruleid", null);
		ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
		ObjectOutputStream output;
		try {
			output = new ObjectOutputStream(byteArray);
			output.writeObject(rule);
			output.close();
			byteArray.close();
			byte[] objectByte = byteArray.toByteArray();
			String string = new String(objectByte);
			System.out.println(string.toString());
			BufferedWriter bw = new BufferedWriter(new FileWriter("a"));
			bw.write(string);
			bw.close();
			BufferedReader br = new BufferedReader(new FileReader("a"));
			string = "";
			String line;

			while ((line = br.readLine()) != null) {
				string += line + "\n";
			}

			string = hexStr2Str(string);
			byte[] objectByte2 = string.getBytes();
			ByteArrayInputStream byteArray2 = new ByteArrayInputStream(
					objectByte2);
			ObjectInputStream input = new ObjectInputStream(byteArray2);
			rule = (RuleMetaMessage) input.readObject();
			System.out.println(rule.getRuleName());
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
